package com.dqhl.community.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.arrownock.exception.ArrownockException;
import com.arrownock.social.AnSocialMethod;
import com.arrownock.social.IAnSocialCallback;
import com.dqhl.community.R;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.User;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.FormatUtils;
import com.dqhl.community.util.JPushUtil;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.util.TimeCountRegisterUtil;
import com.dqhl.community.util.TimeCountUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by guanluocang on 2016/8/29.
 * RegisterActivity
 * 注册
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    private TextView tvSendAuthCode;
    private Button btnRegister;
    private long millisInFuture = Constant.TIMECOUNT_REGISTER; //验证码倒计时
    private EditText et_telPhone, et_password, et_autoCode;
    private User u;
    private Button btn_pwd_show;//显示隐藏密码
    private boolean isHidden = true;
    private ImageView iv_close;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initView();
    }


    /**
     * 实例化对象
     */
    private void initView() {
        tvSendAuthCode = (TextView) findViewById(R.id.tv_send_auth_code);
        btnRegister = (Button) findViewById(R.id.btn_register);
        et_telPhone = (EditText) findViewById(R.id.et_telephone);
        et_password = (EditText) findViewById(R.id.et_pwd);
        et_autoCode = (EditText) findViewById(R.id.et_auth_code);
        btn_pwd_show = (Button) findViewById(R.id.btn_pwd_show);
        iv_close = (ImageView) findViewById(R.id.iv_close);

        tvSendAuthCode.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        btn_pwd_show.setOnClickListener(this);
        iv_close.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                finish();
                break;
            case R.id.tv_send_auth_code: //发送验证码
                doSendAuthCode();
                break;
            case R.id.btn_register: //注册
                doRegister();
//                overlay(LocationCommunityActivity.class); //定位小区
                break;
            case R.id.btn_pwd_show:
                if (isHidden) {
                    et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    btn_pwd_show.setBackgroundResource(R.drawable.ic_pwd_show);
                } else {
                    et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    btn_pwd_show.setBackgroundResource(R.drawable.ic_pwd_hidden);
                }
                isHidden = !isHidden;
                et_password.postInvalidate();
                //切换后将EditText光标置于末尾
                CharSequence charSequence = et_password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }
                break;
        }
    }

    /**
     * 发送验证码
     */
    private void doSendAuthCode() {
        final String strTelPhone = et_telPhone.getText().toString();
        if (!FormatUtils.isMobileNO(strTelPhone)) {
            toast("手机格式不正确");
        } else {
            TimeCountRegisterUtil timeCountUtil = new TimeCountRegisterUtil(this, millisInFuture, 1000, tvSendAuthCode);
            timeCountUtil.start();
            Dlog.e(strTelPhone);
            RequestParams params = new RequestParams(Config.Api.verification);
            params.addBodyParameter("phone", strTelPhone);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e("result:" + result);
                    int errCode = JsonUtils.getErrCode(result);
                    String data = JsonUtils.getInfo(result, "data");
                    if (errCode == 0) {

                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }

        TimeCountRegisterUtil timeCountUtil = new TimeCountRegisterUtil(this, millisInFuture, 1000, tvSendAuthCode);
        timeCountUtil.start();
    }

    /**
     * 注册验证
     */
    private void doRegister() {
        final String strTelPhone = et_telPhone.getText().toString();
        final String strPassword = et_password.getText().toString();
        String strAutoCode = et_autoCode.getText().toString();
        if (!FormatUtils.isMobileNO(strTelPhone)) {
            toast(R.string.toast_telephone_format_error);
        } else if (!FormatUtils.isPwdLegal(strPassword)) {
            toast(R.string.toast_password_format_error);
        } else if (TextUtils.isEmpty(strAutoCode)) {
            toast("请输入验证码");
        } else {
            RequestParams params = new RequestParams(Config.Api.regeister);
            params.addBodyParameter("mobile_number", strTelPhone);
            params.addBodyParameter("password", strPassword);
            params.addBodyParameter("code", strAutoCode);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e("注册：" + result);
                    int errCode = JsonUtils.getErrCode(result);
                    String errMsg = JsonUtils.getInfo(result, "errMsg");
                    String data = JsonUtils.getInfo(result, "data");
                    if (errCode == 0) {
                        u = JSON.parseObject(data, User.class);
                        //同时为箭扣注册
                        registerAnIM(u.getUserid());
                        //设置极光别名
                        JPushAlias(u.getUserid());
                        Dlog.e(u.getUserid());
                        Bundle bundle = new Bundle();
                        bundle.putString("user_id", u.getUserid());
                        forward(LocationCommunityActivity.class, bundle); //定位小区
                    } else {
                        toast(errMsg);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }
    }

    private void registerAnIM(final String userId) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("username", userId);
        params.put("password", userId);
        params.put("password_confirmation", userId);
        params.put("enable_im", true);
        try {
            social.sendRequest(Constant.REGISTER_ANIM, AnSocialMethod.POST, params,
                    new IAnSocialCallback() {
                        @Override
                        public void onFailure(JSONObject response) {
                            try {
                                Log.d("onCreate", response.getJSONObject("meta").getString("message"));
                            } catch (Exception e1) {
                                Log.d("onCreate", e1.toString());
                            }
                        }

                        @Override
                        public void onSuccess(JSONObject response) {
                            try {
                                // 将userid放到SharedPreferences中
                                SharedPreferences.Editor editor = spUserInfo.edit();
//                                editor.putString(Constant.USER_PHONE, name);
                                editor.putString(Constant.ANIM_PHONE, userId);
                                editor.putString(Constant.ANIM_PWD, userId);
                                editor.apply();
                                Log.d("onCreate", response.toString());
                            } catch (Exception e1) {
                                Log.d("onCreate", e1.toString());
                            }
                        }
                    });
        } catch (ArrownockException e) {
            e.printStackTrace();
        }
    }

    //极光推送设置别名
    public void JPushAlias(String userid) {
        if (TextUtils.isEmpty(userid)) {
            Toast.makeText(RegisterActivity.this, R.string.error_alias_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!JPushUtil.isValidTagAndAlias(userid)) {
            Toast.makeText(RegisterActivity.this, R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show();
            return;
        }

        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, userid));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
            }
            JPushUtil.showToast(logs, getApplicationContext());
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
            }
        }
    };
}
